package com.ls.lserp.modules.order.web;

import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.ls.lserp.modules.sys.utils.SystemMessageUtils;
import com.ls.lserp.common.utils.DateUtils;
import com.ls.lserp.common.utils.SystemPath;
import com.ls.lserp.common.utils.excel.template.ExcelTemplate;

import org.apache.commons.collections.map.HashedMap;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import freemarker.template.Configuration;
import groovy.util.ResourceException;

import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.ls.lserp.common.config.Global;
import com.ls.lserp.common.persistence.AjaxDone;
import com.ls.lserp.common.persistence.BaseEntity;
import com.ls.lserp.common.persistence.Page;
import com.ls.lserp.common.utils.CollectionsUtils;
import com.ls.lserp.common.utils.ResourcesUtil;
import com.ls.lserp.common.utils.StringUtils;
import com.ls.lserp.common.web.BaseController;
import com.ls.lserp.modules.order.entity.AuditInfo;
import com.ls.lserp.modules.order.entity.OrderMateriel;
import com.ls.lserp.modules.order.service.OrderMaterielService;

@Controller
@RequestMapping(value = "${adminPath}/customization/nuclearmaterial")
public class OrderMaterielController extends BaseController {

	// 保存 编辑 删除 方法
	@Autowired
	private OrderMaterielService orderMaterielService;
	@Autowired
	Configuration freemarkerConfiguration;
    private SXSSFWorkbook sky = new SXSSFWorkbook ();

	@ModelAttribute
	public OrderMateriel get(@RequestParam(required = false) String id) {

		// 判断id是否为空
		if (StringUtils.isNotBlank(id)) {

			// 执行查询语句 查询基本信息
			return orderMaterielService.get(Long.parseLong(id));
		} else {

			// 若为空，实例化
			return new OrderMateriel();
		}
	}

	/**
	 * @Title: 画面跳转用
	 * @return url
	 */
	@RequiresPermissions("customization:nuclearmaterial:view")
	@RequestMapping(value = { "" })
	public String list(Model model) {
		// 画面跳转
		return "modules/order/orderMateriel";
	}

	/**
	 * @Title: 画面检索
	 * @Description: 查询页面
	 * @param Category
	 * @param request
	 * @param response
	 * @param model
	 * @return searchList
	 * @throws Exception
	 */
	@RequiresPermissions("customization:nuclearmaterial:view")
	@RequestMapping(value = { "searchList" })
	@ResponseBody
	public String searchList(OrderMateriel orderMateriel, HttpServletRequest request, HttpServletResponse response,
			Model model) throws Exception {
		Map<Object, Object> listMap = new HashMap<Object, Object>();
		// ajax回调时使用的一览list名
		request.setAttribute(Global.LIST_NAME, "orderMateriel");
		// 拼接字符串供分页使用
		StringBuilder searchParam = new StringBuilder();
		// 合同订单号
		searchParam.append("&indentNo=");
		searchParam.append(orderMateriel.getIndentNo());
		// 客户
		searchParam.append("&ognizationName=");
		searchParam.append(orderMateriel.getOgnizationName());
		// 款号
		searchParam.append("&styleCustomerNo=");
		searchParam.append(orderMateriel.getStyleCustomerNo());
		// 款式名称
		searchParam.append("&styleNameCn=");
		searchParam.append(orderMateriel.getStyleNameCn());
		// 日期
		searchParam.append("&dateFrom=");
		searchParam.append(orderMateriel.getDateFrom());
		searchParam.append("&dateTo=");
		searchParam.append(orderMateriel.getDateTo());
		// 状态
		searchParam.append("&tabPageStatus=");
		searchParam.append(orderMateriel.getTabPageStatus());
		// 放到Attribute里，使用Global类里面的SEARCH_PAEAM作为key
		request.setAttribute(Global.SEARCH_PAEAM, searchParam.toString());
		
		// 查询一览页面数据
		Page<OrderMateriel> page = orderMaterielService.findList(new Page<OrderMateriel>(request, response),
				orderMateriel);
		// 读取系统路径
		String strUri = request.getContextPath() + Global.getAdminPath();
		// 读取文件生成字符串
		String strHtml = "";
		Map<String, Object> map = new HashedMap();
		map.put("adminUri", strUri);
		map.put("orderMateriers", page.getList());
		map.put("pageNo", page.getPageNo());
		map.put("pageSize", page.getPageSize());
		strHtml = FreeMarkerTemplateUtils
				.processTemplateIntoString(freemarkerConfiguration.getTemplate("orderMateriel.ftl"), map);
		listMap.put("orderMateriel", strHtml);
		listMap.put("page", page.getHtml());

		// ajax返回结果
		return renderString(response, listMap);
	}
	
	/**
     * 进入查看页面
     * @param orderMateriel
     * @param model
     * @return
     */
    @RequiresPermissions("customization:nuclearmaterial:view")
    @RequestMapping(value = "show")
    public String show(OrderMateriel orderMateriel, Model model) {

    	// 将查询结果赋值mvc model层返回jsp页面
        model.addAttribute("orderMateriel", orderMaterielService.getShowInfo(orderMateriel));
        
        // 返回页面地址
        return "modules/order/orderMaterielShow";
    }
    
	/**
	 * 进入编辑页面
	 * @param orderMateriel
	 * @param model
	 * @return
	 */
	@RequiresPermissions("customization:nuclearmaterial:edit")
	@RequestMapping(value = "form")
	public String form(OrderMateriel orderMateriel,Model model,HttpSession session) {
		
		// 创建页面时
		if(orderMateriel.getId()==null){
			// 选择合同订单回调时
			if(orderMateriel.getIndentId()!=null){
					orderMateriel = orderMaterielService.getCreateOrderMaterielInfo(orderMateriel.getIndentId());
			}
		}else{
			orderMateriel = orderMaterielService.getShowInfo(orderMateriel);
		}
		List<OrderMateriel> venderList = orderMaterielService.findVenderList(orderMateriel);
		// 将实体类值赋给mvc model层返回jsp页面
		model.addAttribute("orderMateriel", orderMateriel);
		model.addAttribute("venderList", venderList);
		
		// 返回页面地址
		return "modules/order/orderMaterielCreate";
	}
	
	/**
     * 进入合同订单选择页面
     * @param orderMateriel
     * @param model
     * @return
     */
    @RequiresPermissions("customization:nuclearmaterial:view")
    @RequestMapping(value = "indentSelect")
    public String indentSelect(OrderMateriel orderMateriel, Model model) {
        
        // 将查询结果赋值mvc model层返回jsp页面
        model.addAttribute("orderMateriel", orderMateriel);
        
        // 返回页面地址
        return "modules/order/indentSelect";
    }
    
	/**
	 * @Title: 画面检索
	 * @Description: 查询页面
	 * @param orderMateriel
	 * @param request
	 * @param response
	 * @param model
	 * @return searchIndentList
	 * @throws ResourceException
	 */
	@RequiresPermissions("customization:nuclearmaterial:view")
	@RequestMapping(value = { "searchIndentList" })
	@ResponseBody
	public String searchIndentList(OrderMateriel orderMateriel, HttpServletRequest request, HttpServletResponse response,
			Model model) throws ResourceException {
		Map<Object, Object> listMap = new HashMap<Object, Object>();

		// ajax回调时使用的一览list名
		request.setAttribute(Global.LIST_NAME, "indent");

		// 拼接字符串供分页使用
		StringBuilder searchParam = new StringBuilder();
		searchParam.append("&customerIndentNo=");
		searchParam.append(orderMateriel.getCustomerIndentNo());
		searchParam.append("&styleCustomerNo=");
		searchParam.append(orderMateriel.getStyleCustomerNo());
		searchParam.append("&ognizationName=");
		searchParam.append(orderMateriel.getOgnizationName());
		// 放到Attribute里，使用Global类里面的SEARCH_PAEAM作为key
		request.setAttribute(Global.SEARCH_PAEAM, searchParam.toString());
		
		// 查询一览页面数据
		Page<OrderMateriel> page = orderMaterielService.findIndentList(new Page<OrderMateriel>(request, response),orderMateriel);
		String strHtml = "";
		try{
			Map<String, Object>  map = new HashedMap();
			map.put("indentList",page.getList());
			map.put("pageNo",page.getPageNo());
			map.put("pageSize",page.getPageSize());
			strHtml = FreeMarkerTemplateUtils.processTemplateIntoString(freemarkerConfiguration.getTemplate("indentSelect.ftl"), map);
		}
		catch (Exception e) {
            // 记录日志
            logger.error(e.getMessage(), e);
		}
		
		listMap.put("indent", strHtml);
		listMap.put("page", page.getHtml());

		// ajax返回结果
		return renderString(response, listMap);
	}
	
	/**
     * 核料明细页面
     * @param orderMateriel
     * @param model
     * @return
     */
    @RequiresPermissions("customization:nuclearmaterial:view")
    @RequestMapping(value = "detail")
    public String callOrderMaterielDetail(OrderMateriel orderMateriel, Model model) {
        BigDecimal unusableMQuantity = orderMaterielService.sumMaterialQuantity(orderMateriel);
        // 将查询结果赋值mvc model层返回jsp页面
        model.addAttribute("orderMateriel", orderMateriel);
        model.addAttribute("unusableMQuantity", unusableMQuantity);
        
        
        // 返回页面地址
        return "modules/order/orderMaterielDetail";
    }
    
	/**
     * 采购履历
     * @param orderMateriel
     * @param model
     * @return
     */
    @RequiresPermissions("customization:nuclearmaterial:view")
    @RequestMapping(value = "purchasingResume")
    public String purchasingResume(OrderMateriel orderMateriel, Model model) {

    	// 采购履历一览取得
    	List<OrderMateriel> resultList = null;
    	if(orderMateriel.getMaterialId()!=null){
    	   resultList = orderMaterielService.findContractMeterialList(orderMateriel.getMaterialId());
    	}
    	
    	if(!CollectionsUtils.isEmpty(resultList)){
    		orderMateriel.setContractMeterialList(resultList);
    	}
    	
		// 将查询结果赋值mvc model层返回jsp页面
		model.addAttribute("orderMateriel", orderMateriel);
        
        // 返回页面地址
        return "modules/order/purchasingResume";
    }
    
	/**
	 * 大货单耗选择
	 * @param orderMateriel
	 * @param model
	 * @return
	 */
	@RequiresPermissions("customization:nuclearmaterial:edit")
	@RequestMapping(value = "selectUnit")
	public String selectUnit(OrderMateriel orderMateriel,Model model,HttpSession session,HttpServletResponse response) {

		// 大货单耗选择时，重新查询物料一览信息
		OrderMateriel selectOrderMaterielInfo = orderMaterielService.getSelectOrderMaterielInfo(orderMateriel);
	    orderMateriel.setOrderMaterielList(selectOrderMaterielInfo.getOrderMaterielList());
 	    orderMateriel.setMaterialNum(selectOrderMaterielInfo.getMaterialNum());
 	    orderMateriel.setUnitCost(selectOrderMaterielInfo.getUnitCost());
		
		// 将实体类值赋给mvc model层返回jsp页面
		model.addAttribute("orderMateriel", orderMateriel);
		
		// 返回页面地址
		return "modules/order/orderMaterielCreate";
	}
	
	/**
	 * 保存信息
	 * @return
	 * @throws ResourceException 
	 */
	@RequiresPermissions("customization:nuclearmaterial:edit")
	@RequestMapping(value = "save")
	@ResponseBody
	public String save(OrderMateriel orderMateriel, HttpServletRequest request, Model model, HttpServletResponse response) throws ResourceException {
		
		// 判断id是否为null （判断新建或修改）
		if(orderMateriel.getId()!=null){
			
			// 判断数据是否删除
			OrderMateriel orderMaterielNew=get(orderMateriel.getId().toString());
			
			// 判断数据是否删除
			if(orderMaterielNew==null || BaseEntity.DEL_FLAG_DELETE.equals(orderMaterielNew.getDeleteFlag())){
				// 返回提示信息
				return renderString(response,AjaxDone.error(getText("This_record_has_been_deleted_or_modified_the_operation_failed")));
			}
			// 排他处理
			if(orderMateriel.getVersion()==get(orderMateriel.getId().toString()).getVersion()){
				
				// 版本号加1
				orderMateriel.setVersion(orderMateriel.getVersion()+1);
			}else{
				
				// 返回提示信息
				return renderString(response,AjaxDone.error(getText("This_record_has_been_deleted_or_modified_the_operation_failed")));
			}
		}else{
		
			// 新建版本号赋值1
			orderMateriel.setVersion(1L);
		}
		
		// 保存基准数据及子项数据
		orderMaterielService.saveOrderMateriel(orderMateriel);
			
		// 保存成功返回提示信息
	    return renderString(response,AjaxDone.ok(SystemMessageUtils.getMessageName( "orderMateriel_create_save_msg")));
	}
	
	/**
	 * 审核页面
	 * @param 
	 * @param model
	 * @return
	 */
	@RequiresPermissions("customization:nuclearmaterial:audit")
	@RequestMapping(value = "audit")
	public String audit(OrderMateriel orderMateriel,RedirectAttributes redirectAttributes, Model model,HttpSession session) {
		
		// 履历一览取得
		AuditInfo auditInfo = new AuditInfo();
		// 核料id
		auditInfo.setAuditRelateId(orderMateriel.getId());
		// 阶段（核料)
		auditInfo.setAuditPhaseCd(ResourcesUtil.getConfig("audit_phase_material"));
		AuditInfo resultInfo = orderMaterielService.findAuditInfo(auditInfo);
		
		// 核料id
		resultInfo.setAuditRelateId(orderMateriel.getId());
		// 核料单号
		resultInfo.setAuditRelateNo(orderMateriel.getReserverNo());
		// 阶段
		resultInfo.setAuditPhaseCd(ResourcesUtil.getConfig("audit_phase_material"));

		// 核料状态
		resultInfo.setVersion(orderMateriel.getVersion());
		
		// 审核履历查看
		if(StringUtils.isNotEmpty(orderMateriel.getOnlyShow())){
		  resultInfo.setAuditStatus(1L);
		}
		
		// 将实体类值赋给mvc model层返回jsp页面
		model.addAttribute("auditInfo", resultInfo);
		
		// 返回页面地址
		return "modules/order/auditInfo";
	}
	
	/**
	 * 保存履历信息
	 * @param auditInfo
	 * @param request
	 * @param model
	 * @param response
	 * @return
	 * @throws ResourceException 
	 */
	@RequiresPermissions("customization:nuclearmaterial:edit")
	@RequestMapping(value = "saveAudit")
	@ResponseBody
	public String saveAudit(AuditInfo auditInfo,HttpServletRequest request, Model model, HttpServletResponse response , HttpSession session) throws ResourceException {
		
		// 判断数据是否删除
		OrderMateriel newOrderMateriel = get(Long.toString(auditInfo.getAuditRelateId()));
		// 判断数据是否删除
		if(newOrderMateriel==null || BaseEntity.DEL_FLAG_DELETE.equals(newOrderMateriel.getDeleteFlag())){
			// 返回提示信息
			return renderString(response,AjaxDone.error(getText("This_record_has_been_deleted_or_modified_the_operation_failed")));
		}
		
        // 审核结果已经通过,返回错误提示信息
		AuditInfo pAuditResult = new AuditInfo();
		pAuditResult.setAuditPhaseCd(auditInfo.getAuditPhaseCd());
		pAuditResult.setAuditRelateId(auditInfo.getAuditRelateId());
		if(orderMaterielService.getAuditResult(pAuditResult)>0){
	    	// 返回提示信息
	        return renderString(response,AjaxDone.error(getText("This_record_has_been_deleted_or_modified_the_operation_failed")));
		}
	    
		// 排他处理
		if(auditInfo.getVersion()==get(Long.toString(auditInfo.getAuditRelateId())).getVersion()){
			// 版本号加1
			auditInfo.setVersion(auditInfo.getVersion()+1);
		}else{
			// 返回提示信息
			return renderString(response,AjaxDone.error(getText("This_record_has_been_deleted_or_modified_the_operation_failed")));
		}	
		
	    // 设置核料状态
		if(auditInfo.getAuditResult()==1){
		  	auditInfo.setSampleRequestStatus(ResourcesUtil.getConfig("reserver_meterial_ok"));
		}else{
		   	auditInfo.setSampleRequestStatus(ResourcesUtil.getConfig("reserver_meterial_no"));
		}
		
	    // 保存样品数据
		orderMaterielService.saveAuditInfo(auditInfo);
				
		// 保存成功返回提示信息
	    return renderString(response,AjaxDone.ok(SystemMessageUtils.getMessageName( "audit_ok_msg")));
	}
	
	@RequiresPermissions("customization:nuclearmaterial:edit")
	@ResponseBody
	@RequestMapping(value = "checkOrderMaterial")
	public String checkOrderMaterial(OrderMateriel orderMateriel){
		       	
        	// 核料对象已存在
        	if(orderMaterielService.hasOrderMaterial(orderMateriel)){
        		// 数据重复
                return "false";
        	}else{
        	
        	return "true";
        	}
	}
	
	@RequiresPermissions("customization:nuclearmaterial:edit")
	@ResponseBody
	@RequestMapping(value = "exportFile")
	public String exportFile(OrderMateriel orderMateriel ,HttpServletResponse response){
		try {
            // 模版
            String basePath = SystemPath.getClassPath();
            String tempFilePath = "/" + basePath + "orderMaterial.xlsx";
            ExcelTemplate handle = this.orderMaterielService.exportOrderMateriel(orderMateriel, tempFilePath);
            response.setContentType("application/octet-stream; charset=utf-8");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-disposition", "attachment; filename=" + "orderMaterial_" + orderMateriel.getIndentNo()  +".xlsx");
            OutputStream os = response.getOutputStream();
            // 写到输出流并关闭资源
            handle.writeAndClose(tempFilePath, os);
            os.flush();
            os.close();
            handle.readClose(tempFilePath);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return null;
	}
}
